
package com.kweative.lingua.server.transport;

import com.kweative.lingua.server.ClientPool;
import com.kweative.lingua.server.client.Client;
import java.io.IOException;
import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 *
 * @author henrik
 */
abstract public class Transport extends Thread implements Serializable {
    protected int port;
    protected boolean running = false;
    private int requestsServedSinceGC = 0;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }
    abstract protected boolean attach();
    abstract protected void detach();
    abstract protected Client acceptClient() throws IOException;

    
    public void listen() {
        if (this.attach()) {
            this.setRunning(true);
            start();
        }
    }
    public void close() {
        this.setRunning(false);
        this.detach();
    }


    @Override
    public void run() {
        while(isRunning()) {
            try {
                Client client = this.acceptClient();
                if (client != null) {
                    client.start();
                    requestsServedSinceGC++;
                }
                
                if (requestsServedSinceGC > 5000) {
                    requestsServedSinceGC = 0;
                    new Thread() {
                        @Override
                        public void run() {
                            System.gc();
                        }

                    }.start();
                }
                
            } catch (IOException ex) {
                setRunning(false);
                Logger.getLogger(Transport.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
    }

    public boolean isRunning() {
        return running;
    }

    public void setRunning(boolean running) {
        this.running = running;
    }
    
}
